﻿namespace TelecoSystems.Web.Services.Products
{
    using System;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using System.Web.Security;
    using TelecoSystems.Web.Models;

    /// <summary>
    /// DomainService exposing domain logic over products
    /// </summary>
    [RequiresAuthentication]
    [EnableClientAccess()]
    public class ProductsDomainService : LinqToEntitiesDomainService<TelecoSystemsContainer>
    {
        public IQueryable<Product> GetProducs()
        {
            return this.ObjectContext.Products;
        }

        [RequiresRole("Manager")]
        public void InsertProduct(Product product)
        {
            //Set attributes that are not editable
            product.DateLastModified = product.DateCreated = DateTime.Now;
            product.CreatorID = (Guid)Membership.GetUser().ProviderUserKey;
            
            //Retrieve ID for the new record
            if (this.ObjectContext.Products.Count() > 0)
            {
                //The highest value of Ids increased by 1                
                product.Id = this.ObjectContext.Products.Max(p => p.Id) + 1;
                //product.Id = this.ObjectContext.Products.OrderByDescending(p => p.Id).First().Id + 1;
            }
            else
            {
                //The first record will get Id = 1
                product.Id = 1;
            }

            if ((product.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(product, EntityState.Added);
            }
            else
            {
                this.ObjectContext.Products.AddObject(product);
            }
        }

        [RequiresRole("Manager")]
        public void UpdateProduct(Product currentProduct)
        {
            //Set attributes that are not editable
            currentProduct.DateLastModified = DateTime.Now;

            this.ObjectContext.Products.AttachAsModified(currentProduct, this.ChangeSet.GetOriginal(currentProduct));
        }

        [RequiresRole("Manager")]
        public void DeleteProduct(Product product)
        {
            if ((product.EntityState == EntityState.Detached))
            {
                this.ObjectContext.Products.Attach(product);
            }
            this.ObjectContext.Products.DeleteObject(product);
        }        
    }
}


